import { useMemo } from 'react';
import { Row, Col, Button, message } from 'antd';
import GenernalItem, {
    joinNamePath,
    NamePath,
} from '@/components/GenernalFormItem/GenernalItem';
import ProForm from '@ant-design/pro-form';
import { UploadProps } from 'antd/lib/upload';
import { FormInstance } from '@ant-design/pro-form';
import { ProColumnType } from '@ant-design/pro-table';
import AvatarUpload, { AvatarUploadProps } from '@/components/AvatarUpload';
import useRerender from '@/hooks/useRerender';
import { uploadFile } from '@/service/personnelEntry';
import { visibleByIf } from '@/utils/visible';

interface ActionPersonProps<T> {
    onDelete?: () => void;
    onReset: () => void;
    form?: FormInstance;
    prefix?: NamePath;
    columns: ProColumnType<T>[];
    uploadProps?: AvatarUploadProps['uploadProps'];
}

const IMAGE_FILTER_TYPE = [
    'image/png',
    'image/jpeg',
    'image/jpg',
    'image/gif',
    'image/bmp',
];

export default function ActionPersonItem<T>(props: ActionPersonProps<T>) {
    const [form] = ProForm.useForm(props.form);
    const rerender = useRerender();
    const avatarName = joinNamePath(props.prefix, 'avatar');

    const background = useMemo(
        function renderBackground() {
            const avatars: UploadProps['fileList'] =
                form.getFieldValue(avatarName);
            if (!avatars || !avatars.length) return;

            const avatar = avatars[0];
            if (avatar.response) return JSON.stringify(avatar.response);

            const b = new Blob([avatar.originFileObj!]);
            const url = URL.createObjectURL(b);
            return url;
        },
        [form.getFieldValue(avatarName)],
    );

    /**
     * todo 等待后端接口
     */
    const customerequestHandler: UploadProps['customRequest'] = async (
        options,
    ) => {
        // console.log(options);
        const formdata = new FormData();
        formdata.append('field', 'avatar');
        formdata.append('avatar', options.file);
        const res = await uploadFile(formdata);
        if (res.code !== 200) {
            message.error(res.msg);
            return;
        }
        options.onSuccess?.(res.data.url);
        rerender();
    };

    const beforeUploadHandler = (file: File) => {
        /** 对图片进行过滤 */
        if (!IMAGE_FILTER_TYPE.includes(file.type)) {
            message.error('请正确上传图片格式，如PNG/JPG/JPEG/GIF/BMP格式');
            return false;
        }
    };

    return (
        <GenernalItem<T> prefix={props.prefix} columns={props.columns}>
            <Col span={24}>
                <Row justify="space-between" align="bottom">
                    <Col span={4}>
                        <ProForm.Item
                            name={avatarName}
                            label="头像"
                            required
                            rules={props.uploadProps?.rules}
                        >
                            <AvatarUpload
                                deleteVisible={Boolean(background)}
                                onDelete={() => {
                                    // 删除图片后，不会马上更新视图，需要刷新一下
                                    form.resetFields([avatarName]);
                                    rerender();
                                }}
                                background={background}
                                uploadProps={{
                                    name: avatarName,
                                    fieldProps: {
                                        beforeUpload: beforeUploadHandler,
                                        customRequest: customerequestHandler,
                                    },
                                    ...props.uploadProps,
                                }}
                            />
                        </ProForm.Item>
                    </Col>
                    <Col>
                        <Button
                            onClick={() => {
                                props.onReset?.();
                                rerender();
                            }}
                        >
                            清空
                        </Button>
                        {visibleByIf(
                            Boolean(props.onDelete),
                            <Button
                                style={{ marginLeft: 10 }}
                                onClick={props.onDelete}
                            >
                                删除
                            </Button>,
                        )}
                    </Col>
                </Row>
            </Col>
        </GenernalItem>
    );
}
